<?php
//function template_compile($module, $template, $istag = 0)

function template_compile($template, $folder, $istag = 0)
{
	$tplfile = $folder ? TPL_ROOT.TPL_NAME.'/'.$folder.'/'.$template :  TPL_ROOT.TPL_NAME.'/'.$template;
	
	// aming
	if(!file_exists($tplfile)){
		$tplfile = $folder ? WWW_ROOT.'sites/themes/'.$folder.'/'.$template : WWW_ROOT.'sites/themes/'.$template;
	}
	
	
	// 涉及到自助建站模板文件夹预览、不涉及可以屏蔽此项
	//$tplfile = get_cookie('folder') ? TPL_ROOT.get_cookie('folder').'/'.$template : TPL_ROOT.TPL_NAME.'/'.$template;
	
	
	$content = @file_get_contents($tplfile);
	
	if($content === false) showmessage("$tplfile is not exists!");
	
	// 创建目录
	$compiledtpldir = $folder ?  TPL_CACHEPATH.$folder.'/' :  TPL_CACHEPATH;
	mkdirs($compiledtpldir);
	
	$compiledtplfile = $compiledtpldir.$template.'.tpl.php';
	
	// 将要生成的缓存前面加入需要全局化的变量
	$content = '<?php global $SETTING,$MODULE,$M,$CATEGORY,$TYPE,$AREA,$GROUP,$MODEL,$templateid,$_userid,$_username,$page;@extract($setting);?>'.template_parse($content);
	
	$strlen = file_put_contents($compiledtplfile, $content);
	@chmod($compiledtplfile, 0777);
	
	return $strlen;
}

function template_refresh($tplfile, $compiledtplfile)
{
	$str = file_get_contents($tplfile);
	$str = template_parse($str);
	$strlen = file_put_contents($compiledtplfile, $str);
	@chmod($compiledtplfile, 0777);
	return $strlen;
}

function template_module($module)
{
	//dump($module);
	$files = glob(TPL_ROOT.TPL_NAME.'/'.$module.'/*.html');
	//dump($files);
	if(is_array($files))
	{
		foreach($files as $tpl)
		{
			//$template = str_replace('.html', '', basename($tpl));
			$template = basename($tpl);
			//template_compile($template,$module);
		}
	}
	return TRUE;
}

/*function template_cache()
{
    global $MODULE;
	foreach($MODULE as $module=>$m)
    {
        template_module($module);
	}
	return TRUE;
}*/

function template_cache()
{
    global $MODULE;
	
	$files = glob(TPL_ROOT.TPL_NAME.'/*');
	foreach($files as $file)
	{
		if(!is_dir($file)) continue;
		$modules[] = basename($file);
	}
	foreach($modules as $module)
    {
        template_module($module);
	}
	return TRUE;
} 
/*function template_block($blockid)
{
	$tplfile = TPL_ROOT.TPL_NAME.'/block/'.$blockid.'.html';
	$compiledtplfile = TPL_CACHEPATH.'block_'.$blockid.'.tpl.php';
	if(TPL_REFRESH && (!file_exists($compiledtplfile) || @filemtime($tplfile) > @filemtime($compiledtplfile)))
	{
		template_refresh($tplfile, $compiledtplfile);
	}
	return $compiledtplfile;
}*/

function template_parse($str, $istag = 0)
{
	// 简易替换, 实现模板的可视化编辑,在大型网站下好处特别明显
	$str = str_replace('../skin/',SITE_URL.'themes/'.TPL_NAME.'/skin/',$str);
	$str = str_replace('"skin/','"'.SITE_URL.'themes/'.TPL_NAME.'/skin/',$str);
	
	$str = preg_replace("/([\n\r]+)\t+/s","\\1",$str);
	$str = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}",$str);
	$str = preg_replace("/\{template\s+(.+)\}/","<?php include template(\\1); ?>",$str);
	$str = preg_replace("/\{include\s+(.+)\}/","<?php include \\1; ?>",$str);
	$str = preg_replace("/\{php\s+(.+)\}/","<?php \\1?>",$str);
	$str = preg_replace("/\{if\s+(.+?)\}/","<?php if(\\1) { ?>",$str);
	$str = preg_replace("/\{else\}/","<?php } else { ?>",$str);
	$str = preg_replace("/\{elseif\s+(.+?)\}/","<?php } elseif (\\1) { ?>",$str);
	$str = preg_replace("/\{\/if\}/","<?php } ?>",$str);
	$str = preg_replace("/\{loop\s+(\S+)\s+(\S+)\}/","<?php if(is_array(\\1)) foreach(\\1 AS \\2) { ?>",$str);
	$str = preg_replace("/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/","<?php if(is_array(\\1)) foreach(\\1 AS \\2 => \\3) { ?>",$str);
	$str = preg_replace("/\{\/loop\}/","<?php } ?>",$str);
	$str = preg_replace("/\{\/get\}/","<?php } unset(\$DATA); ?>",$str);
	$str = preg_replace("/\{get\s+([^}]+)\}/e", "get_parse('\\1')", $str);
	$str = preg_replace("/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/","<?php echo \\1;?>",$str);
	$str = preg_replace("/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/","<?php echo \\1;?>",$str);
	$str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/","<?php echo \\1;?>",$str);
	$str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "addquote('<?php echo \\1;?>')",$str);
	$str = preg_replace("/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>",$str);
	return $str;	
	
}

/*function get_tag($tagname)
{
	global $TAG;
    if(!isset($TAG)) $TAG = cache_read('tag.inc.php', TPL_ROOT.TPL_NAME.'/');
	return isset($TAG[$tagname]) ? '<?php echo '.$TAG[$tagname].';?>' : '{tag_'.$tagname.'}';
}*/

function addquote($var)
{
	return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));
}

function get_parse($str)
{
	global $catid;
	
	preg_match_all("/([a-z]+)\=\"([^\"]+)\"/i", stripslashes($str), $matches, PREG_SET_ORDER);
	
	//dump($matches);
	
	foreach($matches as $v)
	{
		$r[$v[1]] = $v[2];
	}
	
	//dump($r);
	extract($r);
	
	if(!isset($dbsource)) $dbsource = '';
	if(!isset($dbname)) $dbname = '';
	if(!isset($sql)) $sql = '';
	if(!isset($rows)) $rows = 0;
	if(!isset($urlrule)) $urlrule = '';
	
	
	if(!isset($page)) $page = 1;
	
	
	//if(!isset($catid)) $catid = 0;
	//if(!isset($catid)) $catid = $catid;
	if(!isset($distinctfield)) $distinctfield = '';
	if(!isset($return) || !preg_match("/^\w+$/i", $return)) $return = 'r';
	
	
	//if(!isset($page)) $page = '0';
	
	// 使用eval来为字符串的变量赋值的时候经常报错往往是因为参数少加了";"
	//$page = $page == '$page' ? eval("$page;") : $page;
		
	//global $page;
	
	// 错误点：如果存在page，而不是page等于或者大于0的时候，这样需要翻页而page=1又省略的情况下看会不到分类栏
	
	//eval("\$page = $page;");
	
	/*if(isset($page))
	//if($page == '$page' || $page)
	{
	    $str = "<?php global \$catid; \$ARRAY = get(\"$sql\", $rows, $page, \"$dbname\", \"$dbsource\", \"$urlrule\",\"$distinctfield\",\"$catid\");         \$DATA=\$ARRAY['data'];\$total=\$ARRAY['total'];\$count=\$ARRAY['count'];\$pages=\$ARRAY['pages'];unset(\$ARRAY);foreach(\$DATA AS \$n=>\${$return}){\$n++;?>";
	}
	else
	{	
		$str = substr($str, -1) == '/' ? "<?php \${$return} = get(\"$sql\", -1, 0, \"$dbname\", \"$dbsource\");?>" : "<?php \$DATA = get(\"$sql\", $rows, 0, \"$dbname\", \"$dbsource\");foreach(\$DATA AS \$n => \${$return}) { \$n++;?>";
	}*/
	
	 $str = "<?php global \$catid; \$ARRAY = get(\"$sql\", $rows, $page, \"$dbname\", \"$dbsource\", \"$urlrule\",\"$distinctfield\",\"$catid\");         \$DATA=\$ARRAY['data'];\$total=\$ARRAY['total'];\$count=\$ARRAY['count'];\$pages=\$ARRAY['pages'];unset(\$ARRAY);foreach(\$DATA AS \$n=>\${$return}){\$n++;?>";
	 
	return $str;
}


// 通过catid找到模板里面主要的GET标签的设置
function template_get_config($catid){


	if(!$catid) return false;

	$C = cache_read("category_$catid.php", '', 1);
	//include_once MOD_ROOT.'template/template.func.php';
	
	// 列表页
	if($C['type'] == 0){
		$template = subcat($catid) ? $C['template_category'] : $C['template_list'];
	}
	else{
		return false;
	}
	
	// 模板完整路径
	$tpl_path = TPL_ROOT.TPL_NAME.'/'.$template;
	
	// 检查路径是否存在包含模板
	if(file_exists($tpl_path)){
		$str = file_get_contents($tpl_path);
	}
	else{
		showmessage("{$tpl_path}路径不存在");
	}
	
	
	// 这里的正则只针对有一个get标签的时候，不准确需要改进，可以调试$a查看正则匹配的结果
	preg_match_all("/\{get\s+([^}]+)\}/e",$str,$a);
	
	//dump($a); 
	
	// 匹配get标签里面的参数
	preg_match_all("/([a-z]+)\=\"([^\"]+)\"/i", stripslashes($a[0][0]), $matches, PREG_SET_ORDER);
	
	//dump($matches);
	
	// 将get标签里面的参数以数组形式保存
	foreach($matches as $v)
	{
		$config[$v[1]] = $v[2];
	}
	
	return $config;
	
}
?>